package cn.itcast.flink.table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * Author itcast
 * Date 2021/7/30 7:03
 * Desc TODO
 */
public class FlinkSQL2 {
    public static void main(String[] args) throws Exception {
        //1.准备环境 获取流执行环境 流表环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        //2.Source
        DataStream<WC> input = env.fromElements(
                new WC("Hello", 1),
                new WC("World", 1),
                new WC("Hello", 1)
        );
        //2.Source 获取 单词信息

        //3.创建视图 WordCount
        tEnv.createTemporaryView("t_wc",input,$("word"),$("frequency"));
        //4.执行查询 单词统计
        Table table = tEnv.sqlQuery("select word,sum(frequency) as frequency from t_wc group by word");
        //5.输出结果 retractStream获取数据流（别名）
        DataStream<Tuple2<Boolean, WC>> result = tEnv.toRetractStream(table, WC.class);
        //6.打印输出结果
        result.print();
        //7.执行
        env.execute();
    }
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class WC {
        public String word;
        public long frequency;
    }
}
